package com.qingluan.filecachetest;

import java.io.File;
import java.io.IOException;

import com.qingluan.filecachetest.ImageDownloader.DealByteCallback;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static  String  ImageUrl = "http://192.168.250.109:8888/image_get";
	private Button bt;
	private ImageView iv;
	private EditText et;
	private TextView tv;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button)findViewById(R.id.get_bt);
        iv = (ImageView)findViewById(R.id.img);
        et = (EditText)findViewById(R.id.edit_url);
        tv = (TextView)findViewById(R.id.now_url);
        
        String newUrl = et.getText().toString();
        if (newUrl.length() >1){
        	ImageUrl = newUrl;
        }
        bt.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				tv.setText(MainActivity.ImageUrl);
				Log.d("I_CACHE","startin ...");
				File file_image = null;
				if (new File(Environment.getExternalStoragePublicDirectory("Do")+"/test.png").exists()){
					try {
						file_image = new File(Environment
								.getExternalStoragePublicDirectory("Do")+"/test.png");
						byte[] data_image = FileCache.readFile(file_image);
						iv.setImageBitmap(BitmapFactory.decodeByteArray(data_image, 0, data_image.length));
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					AlertDialog.Builder dialogBuilder =  new AlertDialog.Builder(MainActivity.this)
						.setTitle("result")
						.setMessage("you geyt this image ,from path\n");
					dialogBuilder.show();
					
				}else {
					ImageDownloader.Download(ImageUrl,new  DealByteCallback(){
	
						@Override
						public void callback(byte[] image) {
							// TODO Auto-generated method stub
							Log.d("I_CACHE","get it");
							Toast.makeText(getApplicationContext(), "connecting", Toast.LENGTH_SHORT).show();
							Context context = getApplicationContext();
							File file = null ;
							String filesPath = Environment.getExternalStoragePublicDirectory("Do").getAbsolutePath();
							if (!new File(filesPath).exists()){
								File filesDir= new File(filesPath);
								filesDir.mkdir();
							}
							
							if (isExternalStorageWritable()){
								if (new File(filesPath+"/test.png").exists()){
									
								}else if (new File(filesPath).exists()){
	
									file = new File(Environment.getExternalStoragePublicDirectory("Do").getAbsolutePath()+"/test.png");
									try {
										
										FileCache.saveFile(file, image);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
										Log.d("I_CACHE","error");
									}
								}
							}
							
							//String data = image.toString();
							Log.d("I_CACHE","path :"+filesPath );
							Log.d("I_CACHE","data is :"+image.toString());
	
							if (new File(context.getFilesDir()+"/test.png").exists()){
								File image_file = new File(Environment.getExternalStoragePublicDirectory("Do").getAbsolutePath()+"/test.png");
								byte[] data_image = null;
								try {
									/*
									 * read byte from local storage 
									 */
									data_image = FileCache.readFile(image_file);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								Bitmap img = BitmapFactory.decodeByteArray(data_image, 0, data_image.length);
								iv.setImageBitmap(img);
								/*new AlertDialog.Builder(context)
									.setTitle("result")
									.setMessage("you geyt this image ,from path\n"+context
												.getFilesDir().toString()).show();
								*/
							}else {
								
								Log.d("I_CACHE","no such file");
							}
						}
			        	
			        });
				}	
			}
        	
        });
        
        //client.post(this.Imageurl, )
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }


    

    
}
